let token = sessionStorage.getItem("token");
let postId = sessionStorage.getItem("post_id");
//导出excel模板

function exportDataTelement(){
    window.open(testurl + "users/template/user") ;
}
// 导出用户excel
function exportData(){
	var url = 'users/export/user';
    var searchValue =  $("#seacrhInput").val();
    if (searchValue != ''){
		url = url + '&username='+searchValue;
        //window.location.href = testurl + '/users/export?username='+searchValue;
    }//else {
        //window.location.href = testurl + '/users/export';
    //}
	
	var ids = "";
	if(checkedLength>0){
        for(var i in moreUserid){
            ids += "," + moreUserid[i];
        }
		ids = ids.substring(1);
    }
	if (ids != ''){
		url = url + '?ids='+ids;
    }
	window.open(testurl + url);
}
//导入用户excel
function importData() {
    var formdata = new FormData();
    var pic = document.getElementById("daoru").files;
    for(var j=0;j<pic.length;j++){
        formdata.append(""+j+"",pic[j]);
    }
    $.ajax({
        url: testurl + "users/leadingin/user",
        type:"post",
        cache: false,
        headers: { "Authorization": "Bearer " + token},
        contentType: false,
        processData: false,
        data:formdata,
        success: function (data) {
            $('#my-alert').modal({ target: '#my-alert' });
            $(".users").html("导入excel");
            $(".alert").html(data.message);
        }
    })
}

//确定模态框
// $("#my-alert").on('close.modal.amui', function () {
//     window.location.reload();
// });

//添加users关闭模态框
$("#users").on('close.modal.amui', function () {

     $("#reset").trigger("click");
     $("#birth").attr("value","");
    $("#work_date").attr("value", "");
    $("input[name='sex']").removeAttr("checked");
    $("input[name='nomination_way']").removeAttr("checked");
    $("#touxiang").attr("src","");
});
//获取选中cheacked的id和个数
var userId = "";
var checkedLength = "";
var moreUserid = [];
//获取value值判断是添加还是修改来调用哪个接口
var isAdd = "";
function check(e){
	moreUserid = [];
    $.each($('#show input:checkbox:checked'),function(){
        userId = $(this).val();
        moreUserid.push(userId);

    });
    checkedLength = $('#show input:checkbox:checked').length;
}
console.log(userId);
//右侧删除
function del(e) {
    var deleteList = [e];
    if(confirm("确定删除用户？")){
        $.ajax({
            type: "post",
            url: testurl + "user/deletes",
            contentType: "application/json",
            headers: { "Authorization": "Bearer " + token },
            data: JSON.stringify({
                "ids": deleteList
            }),
            success: function (data) {
                if (data.success === true) {
                    $(".users").html("删除用户");
                    $(".alert").html("删除成功！");
                    $('#my-alert').modal({ target: '#my-alert' });
                    $('#modal1').modal('close');
                    loadData(1);
                } else {

                    $(".users").html("删除用户");
                    $(".alert").html("删除失败！");
                    $('#my-alert').modal({ target: '#my-alert' });
                    $('#modal1').modal('close');
                    loadData(1);
                }
            },
            error: function (data) {
                alert(data)
            }
        });
    }
  
}
// 右侧修改
function editor(e){
    $("#update").show();
    $("#go").hide();
    $("#getUserId").val(e);
    $("#username").attr("readonly",true);
    $.ajax({
        url: testurl + "users/detail",
        type:"post",
        headers: { "Authorization": "Bearer " + token},
        contentType:"application/json",
        data:JSON.stringify({
            "id":e
        }),
        success:function (data) {
            console.log(data.obj.head_pic)
            $("#id").val(data.obj.id);
            $("#username").val(data.obj.username);
            $("#realname").val(data.obj.realname);
            if(data.obj.sex === "0"){
                $("input[name='sex']").eq(0).prop("checked","checked");
            }else if(data.obj.sex === "1"){
                $("input[name='sex']").eq(1).prop("checked", "checked");
            }
            //头像
            let imgSrc = testurl + data.obj.head_pic;
            if(data.obj.head_pic === undefined){
                imgSrc = "";
            }
            $("#touxiang").attr("src",imgSrc);
            $("#organ").val(data.obj.organ_id);
            $("#shenfen").val(data.obj.post_id);
            $("#presasg").val(data.obj.presasg);
            $("#tuan").val(data.obj.deputy_team);
            $("#address").val(data.obj.address);
            $("#tel").val(data.obj.tel);

            $("#pname1").val(data.obj.company_name);
            $("#pid1").val(data.obj.companyId);

            $("#phone").val(data.obj.phone);
            $("#zip_code").val(data.obj.zip_code);
            $("#remark").val(data.obj.remark);
        }
    });
}

//读取头像
function readFile(){
    let reader = new FileReader;
    let file = this.files[0];
    reader.readAsDataURL(file);
    reader.onload = function(e){
        let base64Code = this.result;
        $("#touxiang").attr("src", base64Code);
    }
}
$(function () {

 
    // 头像
    // let pic1 = document.getElementById("head_pic");
    // pic1.addEventListener('change',readFile,false);
    
    let str2 = "<option value=\"\">请选择</option>"
    let str3 = "<option value=\"\">请选择</option>"
    let str4 = "<option value=\"\">请选择</option>"
  
   
    // //委员团组
    // $.ajax({
    //     url: testurl + "deputy/team/list_nopage",
    //     type: "post",
    //     headers: { "Authorization": "Bearer " + token },
    //     contentType: "application/json",
    //     data: JSON.stringify({
    //         "type": "1"
    //     }),
    //     success: function (data) {
    //         $.each(data.obj, function (index, value) {
    //             str2 += "<option value=\"" + value.id + "\">" + value.name + "</option>"
    //         })
    //         $("#tuan").html(str2);
    //     }

    // });
    //所属单位
    // $.ajax({
    //     url: testurl + "organ/list_nopage",
    //     type: "post",
    //     headers: { "Authorization": "Bearer " + token },
    //     contentType: "application/json",
    //     data: JSON.stringify({}),
    //     success: function (data) {
    //         $.each(data.obj, function (index, value) {
    //             str3 += "<option value=\"" + value.id + "\">" + value.organ_name + "</option>"
    //         })
    //         $("#organ").html(str3);
    //     }

    // });
    //身份
    $.ajax({
        url: testurl + "post/list",
        type: "post",
        headers: { "Authorization": "Bearer " + token },
        contentType: "application/json",
        data: JSON.stringify({}),
        success: function (data) {
            $.each(data.obj, function (index, value) {
                str4 += "<option value=\"" + value.id + "\">" + value.name + "</option>"
            })
            $("#shenfen").html(str4);
        }

    });


    //新建
    $(".buildBtn").click(function () {
        $("#go").show();
        $("#update").hide();
        $("#username").removeAttr("readonly",true);
    });
    //修改
    $(".changeBtn").click(function () {
        $("#go").hide();
        $("#update").show();
        // check();
        if (checkedLength <= 0){
            $('#my-alert').modal({target: '#my-alert'});
            $(".users").html("修改用户");
            $(".alert").html("请选择要修改的用户！");
            return false;
        }else if (checkedLength === 1) {

            $.ajax({
                url:testurl + "users/detail",
                type:"post",
                headers: { "Authorization": "Bearer " + token},
                contentType:"application/json",
                data:JSON.stringify({
                    "id":userId
                }),
                success:function (data) {
                    $("#id").val(data.obj.id);
                    $("#username").val(data.obj.account);
                    $("#realname").val(data.obj.name);
                    //$("#sex").val(data.obj.sex);
                    //头像
                    //let imgSrc = data.obj.head_pic;
                   // $("#touxiang").attr("src",imgSrc);
                    //let organ_id = data.obj.organ_id;
                    // $(".am-selected-list li[data-index='0']").removeClass("am-checked");
                    // $(".am-selected-list li[data-value='"+organ_id+"']").attr("class","am-checked");
                    // $(".am-selected-status").html(data.obj.organ_name);
                    // $('#join_date').datepicker('setValue', data.obj.join_dates);

                    $("#getUserId").val(data.obj.id);
                    $("#presasg").val(data.obj.position);
                    
                    $("#pname1").val(data.obj.company_name);
                    $("#pid1").val(data.obj.companyId);
                    $("#phone").val(data.obj.contacts_phone);
                    $("#shenfen").val(data.obj.post_id);
                    console.log(data.obj)
                }
            });
            isAdd = $(".newBuild input").attr("value");
            console.log(isAdd)
        }else if (checkedLength > 1){
            $('#my-alert').modal({target: '#my-alert'});
            $(".users").html("修改用户");
            $(".alert").html("同时只能选择一个用户,请选择一个！");
            return false;
        }

    });
    //删除
    $(".delBtn").click(function () {
       if (checkedLength <= 0){
           $('#my-alert').modal({target: '#my-alert'});
           $(".users").html("删除用户");
           $(".alert").html("请选择要删除的用户！");
           return false;
       }else {
        if(confirm("是否删除所选用户？")){
            $.ajax({
                type: "post",
                url: testurl + "users/deletes",
                contentType: "application/json",
                headers: { "Authorization": "Bearer " + token },
                data: JSON.stringify({
                    "ids": moreUserid
                }),
                success: function (data) {
                    if (data.success === true) {
                        $(".users").html("删除用户");
                        $(".alert").html("删除成功！");
                        $('#my-alert').modal({ target: '#my-alert' });
                        $('#modal1').modal('close');
                        loadData(1);
                    } else {
                        $(".users").html("删除用户");
                        $(".alert").html("删除失败！");
                        $('#my-alert').modal({ target: '#my-alert' });
                        $('#modal1').modal('close');
                        loadData(1);
                    }
                },
                error: function (data) {
                    alert(data)
                }
            });
        }
    
       }
    });
    //修改密码
    $(".modifyBtn").click(function () {
        if (checkedLength <= 0){
            $('#my-alert').modal({target: '#my-alert'});
            $(".users").html("修改密码");
            $(".alert").html("请选择要修改的用户！");
            return false;
        }else if (checkedLength === 1) {
            $(".newBuild").html("修改密码<a href=\"javascript: void(0)\" class=\"am-close am-close-spin\" data-am-modal-close>&times;</a>");

        }else if (checkedLength > 1){
            $('#my-alert').modal({target: '#my-alert'});
            $(".users").html("修改密码");
            $(".alert").html("同时只能选择一个用户,请选择一个！");
            return false;
        }

    });
    // 提交修改密码
    $("#go2").click(function () {
        var password = $("#password1").val();
        var form3 = $("#form3");
        form3.validator({
            submit: function () {
                var formValidity = this.isFormValid();
                if (formValidity){
                    $.ajax({
                        url:testurl + "users/update_password",
                        type:"post",
                        contentType:"application/json",
                        headers: { "Authorization": "Bearer " + token},
                        data:JSON.stringify({
                            "id":userId,
                            "password":password
                        }),
                        success:function (data) {
                            if (data.success === true) {
                                $(".users").html("修改密码");
                                $(".alert").html("修改成功！");
                                $('#my-alert').modal({target: '#my-alert'});
                                $('#my-popup').modal('close');
                            }else {
                                $(".users").html("修改密码");
                                $(".alert").html("修改失败！");
                                $('#my-alert').modal({target: '#my-alert'});
                                $('#my-popup').modal('close');
                            }
                        }
                    });
                    return false
                } else {
                    return false
                }
            }
        });

    });
    //新增用户
    $("#go").click(function () {
                    //上传头像
                    // let head_pic = "";
                    //     var formdata = new FormData();
                    //     var pic = document.getElementById("head_pic").files;
                    //     for(var j=0;j<pic.length;j++){
                    //         formdata.append(""+j+"",pic[j]);
                    //     }
                    //     $.ajax({
                    //         async:false,
                    //         url:testurl + "users/headpic",
                    //         type:"post",
                    //         data:formdata,
                    //         cache: false,
                    //         contentType: false,
                    //         processData: false,
                    //         success:function (data) {
                    //             head_pic =data.obj;
                    //         }
                    //     });
          
                    let realname = $("#realname").val();
                    let sex = $("input[name='sex']:checked").val();
                    let username = $("#username").val();
                    let organ_id = $("#organ option:selected").val();
                    let post_id = $("#shenfen option:selected").val();
                    let pid1 = $("#pid1").val();
                    let presasg = $("#presasg").val();
                    let tel = $("#tel").val();
                    let home_tel = $("#home_tel").val();
                    let phone = $("#phone").val();
                    let address = $("#address").val();
                    let zip_code = $("#zip_code").val();
                    let deputy_team = $("#tuan option:selected").val();
                    let remark = $("#remark").val();
                    let password = $("#password").val();
                    let str3 = {
                        "account":username,//账号
                        //"password":password,//密码
                        "name":realname,//姓名
                        "companyId":pid1,//单位id
                        "position":presasg,//职位
                        "contacts_phone":phone,//联系方式
                        "post_id":post_id//
                    };
                  
                    // if (isAdd === "0"){
     
                        if(realname === "" ||presasg === ""|| phone === "" ||username === ""){
                             alert("请填写带*必填项！");
                             return false;
                         } else{
                            $.ajax({
                                async: false,
                                headers: { "Authorization": "Bearer " + token },
                                url: testurl + "/users/add",
                                contentType: "application/json",
                                type: "post",
                                data: JSON.stringify(str3),
                                success: function (data) {
                                    if (data.success === true) {
                                        $(".users").html("新建用户");
                                        $(".alert").html(data.message);
                                        $('#my-alert').modal({ target: '#my-alert' });
                                        $('#users').modal('close');
                                        loadData(1);
                                    } else {

                                        $(".users").html("新建用户");
                                        $(".alert").html("新建失败：" + data.message);
                                        $('#my-alert').modal({ target: '#my-alert' });
                                        $('#users').modal('close');
                                        loadData(1);
                                    }
                                },
                                error: function (data) {
                                    console.log(data);
                                }
                            });
                         }
    });
    //修改用户
    $("#update").click(function(){
        let id = $("#getUserId").val();

        // //上传头像
        // let head_pic = "";
        // // if ($("#changePic").val() === "2"){
        // var formdata = new FormData();
        // var pic = document.getElementById("head_pic").files;
        // for (var j = 0; j < pic.length; j++) {
        //     formdata.append("" + j + "", pic[j]);
        // }
        // $.ajax({
        //     async: false,
        //     url: testurl + "users/headpic",
        //     type: "post",
        //     data: formdata,
        //     cache: false,
        //     contentType: false,
        //     processData: false,
        //     success: function (data) {
        //         head_pic = data.obj;
        //     }
        // });
        $("#username").attr("readonly","readonly")
        let realname = $("#realname").val();
        let sex = $("input[name='sex']:checked").val();
        let username = $("#username").val();
        let organ_id = $("#organ option:selected").val();
        let post_id = $("#shenfen option:selected").val();
        let pid1 = $("#pid1").val();
        let presasg = $("#presasg").val();
        let tel = $("#tel").val();
        let home_tel = $("#home_tel").val();
        let phone = $("#phone").val();
        let address = $("#address").val();
        let zip_code = $("#zip_code").val();
        let deputy_team = $("#tuan option:selected").val();
        let remark = $("#remark").val();
        let password = $("#password").val();
        let str3 = {
            "id":id,
            "account":username,//账号
            //"password":password,//密码
            "name":realname,//姓名
            "companyId":pid1,//单位id
            "position":presasg,//职位
            "contacts_phone":phone,//联系方式
            "post_id":post_id//
        };
        if(realname === "" ||presasg === ""|| phone === "" ||username === ""){
            alert("请填写带*必填项！");
            return false;
        }else {
            $.ajax({
                async: false,
                headers: { "Authorization": "Bearer " + token },
                url: testurl + "/users/update",
                contentType: "application/json",
                type: "post",
                data: JSON.stringify(str3),
                success: function (data) {
                    if (data.success === true) {
                        $(".users").html("修改用户");
                        $(".alert").html(data.message);
                        $('#my-alert').modal({ target: '#my-alert' });
                        $('#users').modal('close');
                        loadData(pageNum);
                    } else {

                        $(".users").html("修改用户");
                        $(".alert").html("修改失败：" + data.message);
                        $('#my-alert').modal({ target: '#my-alert' });
                        $('#users').modal('close');
                        loadData(pageNum);
                    }
                },
                error: function (data) {
                    console.log(data);
                }
            });
        }



    });
    //选中所有的checkbox框
    $('#checkAll[name="selectAll"]').click(function(){
        // alert(this.checked);
        if($(this).is(':checked')){
            $('#show input[name="selectAll"]').each(function(){
                //此处如果用attr，会出现第三次失效的情况
                $(this).prop("checked",true);
            });
        }else{
            $('input[name="selectAll"]').each(function(){
                $(this).removeAttr("checked",false);
            });
            //$(this).removeAttr("checked");
        }

    });
    //查询用户列表
    //页数
    var pages =1;
    // 查找用户
    var realname ="";
        $("#searchValue").click(function () {
            realname = $("#seacrhInput").val();
            loadData();
        });

    function loadData(pageNum){
        $.ajax({
            url:testurl + "users/list",
            type:"post",
            headers: { "Authorization": "Bearer " + token},
            contentType: "application/json",
            data:JSON.stringify({
                "pageNum": pageNum,
                "name": realname,
            }),
            success: function (data) {
                let userList = data.obj;
                console.log(userList)
                ssd = Math.ceil(data.pageTotal/data.pageSize);
                pages = ssd;
                str = "";
                $.each(userList ,function (index,values) {
                    if(values.phone === null){
                        values.phone = "";
                    }
                    if (values.email === null){
                        values.email = "";
                    }
                    if(values.post_name === undefined){
                        values.post_name = "";
                    }
                    if (values.presasg === undefined){
                        values.presasg = "";
                    }
                    if(values.phone === undefined){
                        values.phone = "";
                    }
                    if(values.tel === undefined){
                        values.tel = "";
                    }
                    if(values.organ_name === undefined){
                        values.organ_name = "";
                    }
                    if(values.contacts_phone === undefined){
                        values.contacts_phone = "";
                    }
                    // "account": "0001",//账号
                    // "name": "李哥庄",//姓名
                    // "company_name": "李哥庄镇政府",//单位名称
                    // "position": "职位",//职位
                    // "contacts_phone": "8888123",//联系方式
                    // "post_name": "管理员"//角色
                    str += "   <tr class=\"gradeX\">\n" +
                        "                            <td><input name='selectAll' onchange='check("+values.id+")' class='checked' value="+values.id+" type='checkbox'></td>\n" +
                        "                            <td>" + values.account+"</td>\n" +
                        "                            <td><a style=\"cursor:pointer\" onclick=\"getUsersDetail("+values.id+")\" data-am-modal=\"{target: '#checkusers'}\">" + values.name +"</a></td>\n" +
                        
                        "                            <td>" + values.company_name+"</td>\n" +
                        "                            <td>" + values.position+"</td>\n" +
                        "                            <td>" + values.contacts_phone+"</td>\n" +
                        "                            <td>" + values.post_name+"</td>\n" +
                         "                            <td>\n" +
                                "                                <div class=\"tpl-table-black-operation\">\n" +
                                // "                                    <a  data-am-modal=\"{target: '#users'}\"  onclick='editor(\"" + values.id + "\");' href=\"javascript:;\">\n" +
                                // "                                        <i class=\"am-icon-pencil\"></i> 修改\n" +
                                // "                                    </a>\n" +
                                // "                                    <a href=\"javascript:;\" onclick='del(\"" + values.id + "\")' class=\"tpl-table-black-operation-del\">\n" +
                                // "                                        <i class=\"am-icon-trash\"></i> 删除\n" +
                                // "                                    </a>\n" +
                                "                                    <a onclick=\"getUsersDetail(" + values.id + ")\" data-am-modal=\"{target: '#checkusers'}\" href=\"javascript:;\">\n" +
                                "                                        <i class=\"am-icon-check\"></i> 查看\n" +
                                "                                    </a>\n" +
                                "                                </div>\n" +
                                "                            </td>\n"+
                                 "                        </tr>";
                    // console.log(values.id)
                });
                $("#show").html(str);
                $(".pagenum_1").html(pages)
                if (pageNum >= pages) {
                    pageNum = pages
                }
                $(".strip_1").html(data.pageSize)
                $(".page_1").html(pageNum)
            }
        });
    }
    loadData(1);
    //分页
    var pageNum = 1;
    $(".first").click(function(){
        pageNum =1;
        loadData(pageNum);
        $(this).parents("li").addClass("am-active");
        $(this).parents("li").siblings().removeClass("am-active");
    });
    $(".last").click(function(){
        pageNum = pages;
        loadData(pageNum);
        $(this).parents("li").addClass("am-active");
        $(this).parents("li").siblings().removeClass("am-active");
    });
    $(".up").click(function(){
        if(pageNum === 1){
            return false;
        } else{
            pageNum--;
            loadData(pageNum);
        }
        $(this).parents("li").addClass("am-active");
        $(this).parents("li").siblings().removeClass("am-active");
    });
    $(".down").click(function(){
        if(pageNum === pages){
            return false;
        } else{
            pageNum++;
           
            loadData(pageNum);
        }
        $(this).parents("li").addClass("am-active");
        $(this).parents("li").siblings().removeClass("am-active");
    });
    $(".go_page_search1").click(function () {
        pageNum = $(".go_page_1").val().trim();
        if (isNaN(pageNum) || pageNum == "") {
            $(".show_desc").html("只能为数字");
            $('#my-alert').modal({ target: '#my-alert' });
            $(".go_page_c").val("")
            return
        }
        loadData(pageNum);
        $(".go_page_c").val("");
    });


});

function getUsersDetail(e){
    $.ajax({
        url: testurl + "users/detail",
        type: "post",
        headers: { "Authorization": "Bearer " + token },
        contentType: "application/json",
        data: JSON.stringify({
            "id":e
        }),
        success:function(data){
            console.log(data)
            $("#username2").html(data.obj.account);
            $("#realname2").html(data.obj.name);
            $("#sex2").html(data.obj.company_name);
            $("#presasg2").html(data.obj.contacts_phone);
            $("#organ2").html(data.obj.position);
            $("#tel2").html(data.obj.post_name);
            // $("#home_tel2").html(data.obj.home_tel);
            // $("#remark2").html(data.obj.remark);
            // $("#deputy_team2").html(data.obj.deputy_team_name);
            // $("#shenfen2").html(data.obj.post_name);
            // $("#organ2").html(data.obj.organ_name);
            // $("#zip_code2").html(data.obj.zip_code);
            // $("#address2").html(data.obj.address);
        }
    })
}